<template>
  <div>
    <el-tag
      :key="index"
      v-for="(item,index) in dynamicTags"
      closable
      :disable-transitions="false"
      @close="handleClose(item.id)">
      {{item.name}}
    </el-tag>
    <el-input
      class="input-new-tag"
      v-if="inputVisible"
      v-model="inputValue"
      ref="saveTagInput"
      size="small"
      @keyup.enter.native="handleInputConfirm"
      @blur="handleInputConfirm"
    >
    </el-input>
    <el-button v-else class="button-new-tag" icon="el-icon-plus" size="small" @click="showInput">新增</el-button>

  </div>
</template>
<script>
  export default {
    components: {
    },
    props:{
      categoryId: null
    },
    watch:{
      categoryId:function (newVal,oldVal) {
        this.loadData(newVal)
      }
    },
    data() {
      return {
        dynamicTags: [],
        inputVisible: false,
        inputValue: ''
      }
    },
    mounted: function () {
      this.loadData(this.categoryId)
    },
    methods: {
      loadData(id){
        let that = this;
        this.utils.request.queryListAllProductParameter({categoryId:id}, function (res) {
          let data = res.data;
          if(data){
            that.dynamicTags = data
          }
        });
      },
      handleClose(id) { // 删除
        let that = this;
        this.utils.request.deleteProductParameter(id, function (res) {
          if(res.code=='0000'){
            let index = that.dynamicTags.findIndex(item => {
              return item.id == id
            })
            that.dynamicTags.splice(index, 1);
            that.$message.success("删除成功")
          } else {
            that.$message.error("删除成功")
          }
        });
      },
      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      handleInputConfirm() { // 新增
        let inputValue = this.inputValue;
        if (inputValue) {
          let that = this;
          this.utils.request.addProductParameter({
            categoryId: that.categoryId,
            name: inputValue
          }, function (res) {
            that.inputVisible = false;
            that.inputValue = '';
            if(res.code=='0000'){
              that.dynamicTags.push({
                id: res.data,
                name: inputValue
              });
              that.$message.success("新增成功")
            } else {
              that.$message.error("新增失败")
            }
          });
        } else {
          this.inputVisible = false;
          this.inputValue = '';
        }
      }
    }
  }
</script>
<style scoped lang="scss">
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
